package com.jincp.common.http;

import android.util.Log;

import com.jincp.common.utils.GsonUtil;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * =========================================================
 * @ProjectName: 实体类型回调接口
 * @ClassName: HttpBeanCallback
 * @Description:
 * @Author: jincp
 * @CreateDate: 2019/9/3 09:42
 * =========================================================
 */
public abstract class HttpBeanCallback<Result> implements IHttpCallback {

    @Override
    public void onResponseSuccess(int code, String result) {
        Result resultObject = GsonUtil.getInstance().jsonToObject(result, getGenericType());
        if (resultObject == null) {
            onResponseFailure(HttpProcessor.ERROR_FROM_PARSER, "解析错误");
        } else {
            onSuccess(code, resultObject);
        }
    }

    public abstract void onSuccess(int code, Result result);

    @Override
    public void update(long currentLength, long totalLength, boolean done) {
        Log.d("HttpBeanCallback", "currentLength = " + currentLength +  "   totalLength = " + totalLength);
    }

    /**
     * 返回泛型 .class
     * @return
     */
    protected final Type getGenericType() {
        Type superclass = getClass().getGenericSuperclass();
        if (superclass instanceof ParameterizedType) {
            Type[] params = ((ParameterizedType) superclass).getActualTypeArguments();
            if (params.length > 0)
                return params[0];
        }
        return Object.class;
    }
}
